<template>
  <div class="CarList">
    <!-- 顶部 -->
    <myheader title="传智博客 黑马程序员Vue.js"></myheader>

    <!-- 购物车列表 -->
    <div class="carListBox">
      <p v-show="goodslist.length === 0" class="empty">🤣 购物车空空如也~~</p>
      <div class="goodsitem" v-for="(item, index) in goodslist" :key="item.id">
        <div class="swipeBox">
          <!-- 选中商品 -->
          <van-switch v-model="item.goods_checked" />
          <!-- 卡片列表 -->
          <van-card
            :title="item.title"
            :thumb="item.thumb_path"
            class="cardList"
            @click="$router.push({ path: `/GoodsDetial/${item.id}` })"
          >
            <template #bottom>
              <span class="goodsPrice">￥{{ item.sell_price * item.num }}</span>
              <!-- 编辑数量 -->
              <van-stepper
                integer
                v-model="item.num"
                @plus="plusNum(item.id)"
                @minus="minusNum(item.id)"
              />
              <!-- 删除商品 -->
              <span @click.stop="delGoods(index, item.id)">删除</span>
            </template>
          </van-card>
        </div>
      </div>

      <!-- 选中数组 -->
      <!-- <p>商品列表选中情况：{{ goodsCheck }}</p> -->
      <div class="goodsCheckList">
        <van-icon
          name="fire-o"
          size="25"
          v-for="(i, d) in goodsCheck"
          :key="d"
          :color="i ? '#ee0a24' : 'gray'"
        />
      </div>
    </div>

    <!-- 结算 -->
    <!-- 原设计样式 -->
    <!--  <div class="account">
      <div class="account_detail">
        <p class="account_sum">总计(不含运费)：</p>
        <span
          >已经选择商品 {{ checkedKindNum }} 件，总价￥{{ totalPrice }}元</span
        >
      </div>
      <van-button
        color="#ef4f4f"
        class="account_btn"
        @click="$toast('跳转到订单页面')"
        >去结算</van-button
      >
    </div> -->

    <div class="orderSubBox">
      <!-- <p class="account_sum2" v-show="goodslist.length !== 0">总计(不含运费)：</p> -->
      <van-submit-bar
        :price="totalPrice * 100"
        button-text="提交订单"
        label="总价:"
        class="orderSubmit"
        :disabled="goodslist.length === 0"
        tip-icon="info-o"
        @submit="$toast('跳转到订单页面')"
      >
        <div class="decribtion">
          <p>已经选择商品 {{ checkedKindNum }} 件</p>
        </div>
        <template #tip v-if="goodslist.length === 0">
          购物车没有商品哦，请先加商品~
        </template>
      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import { getShopcarList } from "../../Api/shopcar.js";
import myheader from "../../components/myheader.vue";
import { bus } from "@/utils/bus.js";

export default {
  data() {
    return {
      goodslist: [],
    };
  },
  computed: {
    //  选中商品总价
    totalPrice() {
      let sPrice = 0;
      this.goodslist
        .filter((g) => g.goods_checked)
        .forEach((v) => {
          sPrice += v.sell_price * v.num;
        });
      return sPrice;
    },

    // 选中商品总数量
    checkedKindNum() {
      let sNum = this.goodslist.filter((g) => g.goods_checked).length;
      return sNum;
    },
    // 获取商品选中状态
    goodsCheck() {
      return this.goodslist.map((v) => v.goods_checked);
    },
  },
  // 监听商品数量
  watch: {
    goodslist: {
      handler(newVal, oldVal) {
        let sNum = 0;
        newVal.forEach((v) => {
          sNum += v.num;
        });
        // 修改本地存储
        this.changeLocalStorage();
        // 传送商品数量
        bus.$emit("getTotalNum1", { type: "update", count: sNum });
      },
      deep: true,
    },
  },

  async mounted() {
    this.init();
  },

  components: {
    myheader,
  },
  methods: {
    // 初始获取商品列表
    async init() {
      // 获取本地购物车商品数据
      let getGoodskey = JSON.parse(localStorage.getItem("addShoppingCar"));

      if (!getGoodskey) return;

      let goodsObj = {};
      getGoodskey.forEach((g) => {
        if (!goodsObj[g.id]) {
          goodsObj[g.id] = g.count;
        } else {
          goodsObj[g.id] += g.count;
        }
      });
      // 获取商品id字符串
      const keyString = Object.keys(goodsObj).join(",");
      //  接口获取购物车商品列表
      if (keyString) {
        let res = await getShopcarList(keyString);
        this.goodslist = res.data.message.map((g) => {
          g.num = goodsObj[g.id];
          g.goods_checked = false;
          return g;
        });
      }
    },

    // 修改本地存储
    changeLocalStorage() {
      let handleList = [];
      this.goodslist.forEach((g) => {
        handleList.push({ id: g.id, count: g.num });
      });
      localStorage.setItem("addShoppingCar", JSON.stringify(handleList));
    },

    // 删除商品
    async delGoods(index, delId) {
      // 商品列表删除商品
      this.goodslist.splice(index, 1);
      // 修改本地存储商品
      this.changeLocalStorage();
      this.$toast.success("删除商品成功");
    },

    // 步进器 阻止事件冒泡
    plusNum(id) {
      event.stopPropagation(); // + 阻止事件冒泡
      console.log(id);
    },
    minusNum(id) {
      event.stopPropagation(); // - 阻止事件冒泡
      console.log(id);
    },
  },
};
</script>

<style lang="less" scoped>
.CarList {
  text-align: left;
  .carListBox {
    padding-bottom: 50px;
    .empty {
      color: orange;
      font-size: 14px;
      padding: 10px;
    }
    // .delete-button {
    //   height: 100%;
    // }
    .goodsitem {
      .swipeBox {
        display: flex;
        align-items: center;
        padding: 0 10px;

        /deep/ .van-card {
          // width: 100%;
          flex: 1;
          text-align: left;
          padding: 8px 0;

           .van-card__title {
            color: #0094ff;
            font-size: 16px;
          }

          .goodsPrice {
            font-size: 17px;
            color: red;
          }

          .van-card__bottom {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 34px;
            width: 100%;
          }
        }
      }
    }

    .goodsCheckList {
      display: flex;
      padding: 10px;
      flex-wrap: wrap;
      i {
        padding-right: 10px;
      }
    }
  }

  /*  .account {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    background-color: #eeeeee;
    height: 90px;

    .account_detail {
      text-align: left;
      color: black;

      span {
        font-size: 12px;
        line-height: 30px;
      }
      .account_sum {
        font-size: 18px;
        font-weight: 700;
        line-height: 40px;
      }
    }
    .account_btn {
      border-radius: 5px;
      font-size: 18px;
    }
  } */
  .orderSubBox {
    background-color: #eeeeee;
    margin-top: 20px;
    .account_sum2 {
      font-size: 15px;
      font-weight: 700;
      // line-height: 40px;
      padding-left: 10px;
      padding-top: 13px;
    }
    .orderSubmit {
      // height: 50px;
      bottom: 50px;
      width: 100%;
      border-top: 1px solid #ddd;
      border-bottom: 1px solid #ccc;
      /deep/ .van-submit-bar__tip {
        line-height: 0.5;
      }
      /deep/ .van-submit-bar__bar {
        padding: 0 10px;
        height: 52px;

        .van-submit-bar__button {
          width: 86px;
          height: 38px;
        }

        .van-submit-bar__text {
          font-size: 12px;
          padding-right: 8px;
        }
        .van-submit-bar__price {
          padding-left: 4px;
        }
      }
      p {
        font-size: 12px;
        height: 20px;
        line-height: 26px;
        vertical-align: bottom;
      }
    }
  }
}
</style>